<template>
    <div class="goods-kind">
        <h3>产品管理</h3>
        <el-button  @click="tabChanged()" :class="{active:index==2}" class="tab" plain>全部</el-button>
        <el-button  @click="tabsecond()" :class="{active:index==0}"  class="tab" plain>已上架</el-button>
        <el-button  @click="tabthree()" :class="{active:index==1}"   class="tab" plain>未上架</el-button>
        <!-- <template>
            <el-tabs v-model="activeName" @tab-click="handleClick">
                <el-tab-pane label="全部" name="first"  @click="tabChanged()"></el-tab-pane>
                <el-tab-pane label="已上架" name="second" @click="tabsecond()"></el-tab-pane>
                <el-tab-pane label="未上架" name="third"  @click="tabthree()"></el-tab-pane>
               
            </el-tabs>
        </template> -->
        <el-form  v-model="search" >
        <el-row>
            <el-col class="flexCenter" :span="10">
            <span>产品名称:</span>
            <el-input
                clearable
                class="ipts"
                placeholder="请输入要查询的产品名称"
                size="small"
                v-model="search.goodName"
            ></el-input>
            </el-col>
            <el-col class="flexCenter" :span="10">
            <span>产品编码:</span>
            <el-input
                clearable
                class="ipts"
                placeholder="请输入要查询的产品编码"
                size="small"
                v-model="search.goodId"
            ></el-input>
            </el-col>
        <el-col class="flexCenter" :span="10">
          <span>产品来源:</span>
            <el-select
                class="bot"
                @change="selectOrigin"
                size="small"
                clearable
                v-model="search.channel"
                placeholder="请选择"
            >
                <el-option
                v-for="item in placeList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
                ></el-option>
            </el-select>
        </el-col>
            <el-col class="flexCenter" :span="10">
            <span>产品状态:</span>
            <el-select
                class="bot"
                @change="selectStatus"
                size="small"
                clearable
                v-model="search.goodStatus"
                placeholder="请选择"
                :disabled="index != 2"
            >
                <el-option
                v-for="item in goodsStatus"
                :key="item.value"
                :label="item.label"
                :value="item.value"
                ></el-option>
            </el-select>
            </el-col>
            <el-col class="btn" :span="3">
            <el-button size="small" type="primary" @click="doSearch"
                >查询</el-button>
            </el-col>
        </el-row>
        </el-form>
        <el-form style="height:60px;">
            <el-col :span="10">
                <el-button type="primary" @click="creatproucts()">+新增</el-button>
                <el-button type="primary" @click="putonsale" :disabled="isshow" >上架</el-button>  
                <el-button type="primary" @click="pulloffsale" :disabled="isshow" >下架</el-button>	
            </el-col>
            <el-col :span="10" style="display:flex; justify-content: flex-start;align-items: flex-end;">
                <!-- <el-form-item style="display:flex;height:18px;position:relative;left:290px;"> -->
                    <el-upload
                    class="upload-demo"
                    ref="upd"
                    accept=".csv, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel"
                    :action= setUrl
                    :headers="headers"
                    :on-success="successUp"
                    :before-upload="beforeUpd"
                    :show-file-list="false"
                    
                    >
                        <el-button type="primary">批量上传</el-button>
                    </el-upload>
                                    <!-- <el-button type="primary" @click="submitForm('formData')" style="margin-left:300px;">批量上传</el-button> -->
                                    <!-- <a href="http://tklifeacuat.mobile.taikang.com/blank/good_blank.xlsx" style="margin-left:20px;color:#3280FC;border-bottom:1px solid #3280FC;padding-bottom:10px;">下载模板</a>   -->
                                
                <!-- </el-form-item>  -->
                            
                <a href="http://tklifeacuat.mobile.taikang.com/blank/good_blank.xlsx" style="margin-left:20px;color:#3280FC;border-bottom:1px solid #3280FC; height: 27px;">下载模板</a>
            </el-col> 
            
        </el-form>
        <el-table :data="list" this.loading = true  style="width: 100%" @selection-change="handleSelectionChange"  ref="multipleTable">

            <el-table-column type="selection" width="55" fixed></el-table-column>
            <el-table-column type="index" label="序号" fixed></el-table-column>
             <el-table-column label="产品编号" prop="goodId" width="120" fixed>
            </el-table-column>
            <el-table-column label="产品名称" prop="name" width="120" fixed></el-table-column>
            <el-table-column label="产品主图" prop="picUrl" width="120">
                <template slot-scope="scope">
                    <img :src="scope.row.picUrl">
                </template>
            </el-table-column> 
            <el-table-column label="现/划线价" width="80" >
                <template slot-scope="scope">
                      {{scope.row.marketPrice/100}}/{{scope.row.originalPrice == 0 ? "" : scope.row.originalPrice/100}}
                </template>
            </el-table-column>
        
            <el-table-column label="产品状态" width="80" prop="goodStatus">
                <template slot-scope="scope">
                    {{scope.row.goodStatus|statusFilter}}
                </template>
            </el-table-column>       
            <el-table-column label="产品来源" prop="channel" width="120">
                 <template slot-scope="scope">
                    {{scope.row.channel |channelFilter}}
                </template>
            </el-table-column>
            <el-table-column label="总销量" prop="salesVolume" width="80"></el-table-column>
            <el-table-column label="创建时间" prop="gtmCreate" width="120"></el-table-column>
            
            <el-table-column label="操作" width="400">
                <template slot-scope="scope">
                    <el-button
                        size="mini"
                        @click="check(scope.row.id) ">查看</el-button>
                    <el-button
                        size="mini"
                        type="Success"
                        @click="handleEdit(scope.row.id)">编辑</el-button>
                    <el-button
                        size="mini"
                        type="Success"
                        @click="OfftheShelf(scope.$index, scope.row)" v-show="scope.row.goodStatus==0"> <span v-show="scope.row.goodStatus==0">下架 </span>
                        </el-button>    
                        <el-button
                        size="mini"
                        type="Success"
                        @click="grounding(scope.$index, scope.row)" v-show="scope.row.goodStatus==1"> <span v-show="scope.row.goodStatus==1">上架 </span>
                        </el-button>  
                    <el-button
                        size="mini"
                        type="danger"
                    @click="handleDelete(scope.$index, scope.row)">删除</el-button>
                    <el-button
                        size="mini"
                        v-show="none"
                    type="primary"
                    @click="sort(scope.$index, scope.row)">修改排序</el-button>
                </template>
            </el-table-column>
        </el-table> 
                
            <el-pagination
             style="text-align: right; margin-top: 20px"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                :current-page="pageNum"
                :page-size="pageSize"
                :page-sizes="[10, 200, 300, 400]"
                :total="total"
                layout="total, sizes, prev, pager, next, jumper">
            </el-pagination>
            <el-dialog
                title="请输入排序号"
                :visible.sync="dialogVisible"
                width="30%"
                >
                <el-input v-model="sortNumber"></el-input>
                <span slot="footer" class="dialog-footer">
                    <el-button @click="dialogVisible = false">取 消</el-button>
                    <el-button type="primary" @click="submitDia">确 定</el-button>
                </span>
            </el-dialog>
    </div>
</template>

<script>
import goodsApi from "@/api/lejv/goods"
import _ from "lodash" //引入lodash 
import { getToken } from "@/utils/auth";
import {queryGoodsList,delGoods,sortGoods,updateGoods,queryGoodsdetail,batchGoods} from "@/api/lejv/goods"
import { Row } from 'element-ui';
export default {
    name:"goodsKind",
    data() {
        return {
            dialogVisible: false,
            sortNumber:"",
            selectRow:"",
            setUrl:'',
        search: {
            goodName: "",
            goodId:'',
            showStatus: "",
            channel: "",
      },
        goodsStatus: [
            {
            value:"0",
            label:"已上架"
            },
            {
            value:"1",
            label:"已下架"
            },
      ],
      placeList: [
        {
          value:"A",
          label:"健投"
        },
        {
          value:"B",
          label:"拜博"
        },
      ],
        headers: { Authorization: getToken() },
        value:"",
        isshow:true,
        // activeName:'first',
        tableData: [],
        index:"2",
        dialogFormVisible: false,
        // offset: 0,
        // limit: 3,
        loading: false,
        total: 0,
        pageSize:10,
        pageNum:1,
        table:[],
        disabled:false,
        multipleSelection: [],
        params:[],
        flie:"",
        start:'',
        none:true
    };
    },
     filters:{
        statusFilter(status){
            if (status == 0) return  "已上架"
            if (status == 1) return "已下架"
        },
        channelFilter(chanel){
            if(chanel=="B") return "拜博"
            if(chanel=="A") return "健投"
        }
    },
    computed: {
        list(){
            if(this.index == "2"){
                return this.tableData
            }else{
                return this.tableData.filter(item =>item.goodStatus == this.index)
            }
        // list(){
        //     if(this.index=="2"){
        //         return this.tableData
        //     }else if(this.index=="0"){
        //         if(this.search.goodsStatus=="0"){
        //             return this.tableData.filter(item =>item.goodStatus == this.index)
        //         }else {
        //              this.tableData=[]
        //         }
        //     }else if(this.index=="1"){
        //         if(this.serach.goodstatus=="1"){
        //             return this.tableData.filter(item =>item.goodStatus == this.index)
        //         }else {
        //              this.tableData=[]
        //         }
        //     }
            
        },
        // count(){
        //     if(this.index == "2"){
        //         return this.total
        //     }else{
                
        //         return this.list.length
        //     }
        // },
    },
    created() {
        this.queryGoodsList()
        this.index = "2"
        this.setUrl = window.location.host.indexOf('tk') != -1 ? (window.location.protocol + "//" + window.location.host + "/be/admin/goods/batch") : "http://tklifeacuat.mobile.taikang.com/be/admin/goods/batch"
    },
    mounted() {

    },
    methods: { 
      tabChanged(){
         this.index = "2"
         this.none=true;
         this.search.goodStatus = ''
         this.queryGoodsList()
        //  this.$forceUpdate()
      },
      tabsecond(){
          this.index = "0";
          this.none=true;
          this.search.goodStatus = '0'
          this.queryGoodsList()     
           },
      tabthree(){
          this.index = "1",
          this.none=false,
          this.search.goodStatus = '1'
          this.queryGoodsList()  
      },
        creatproucts(){
            this.$router.push("product-access-mode")
        },
        //查询列表
        queryGoodsList(){
            this.loading = true
            // let params = JSON.parse(JSON.stringify(this.search))
            let obj ={
                pageNum:this.pageNum,
                pageSize:this.pageSize,
                ...this.search
            } 

            obj = _.pickBy(obj,(item) =>item) //使用lodash进行过滤参数为空的搜索条件
            // if(params.goodName){
            //     params.goodName = encodeURI(params.goodName)
            //     console.log(params.goodName);
                
            // }
            // let str = '?pageNum='+this.pageNum + '&pageSize='+this.pageSize + '&goodId='+this.search.goodId+ '&goodName='+this.search.goodName+ '&goodStatus='+this.search.goodStatus+ '&channel='+this.search.channel
            goodsApi.queryGoodsList(obj)
            .then(res=>{
                 if(res.msg == "success"){    
                        this.loading = false
                        if(res.data){
                            this.table= res.data.goods
                            console.log(res)
                            this.tableData= res.data.goods
                            this.total= res.data.totalElements
                        }else{
                            this.tableData=[]
                        }  
                    }
            }).catch(res=>{
                this.loading = false
                console.log(res);
        
      })
        },
     //选择状态
    selectStatus(val){
      console.log(val);
      this.search.showStatus = val
    },
   
    //选择来源
    selectOrigin(val){
        console.log(val);
        this.search.channel = val
     },
    
    doSearch() {
        this.pageNum = 1
        this.queryGoodsList()
     },

    //查看
    check(id){
            this.$router.push({name:"checkproduct",params:{detailid:id}})
    },
    //编辑
    handleEdit(editid){
        // console.log(row,222,row.id)
        this.$router.push({name:"editproduct",params:{editid}})
    },
    //批量上架
    putonsale(){
        console.log(this.multipleSelection)
        let data=[]
        this.multipleSelection.forEach(function(x){
            data.push(x.id)
         })
         this.$confirm('是否确认将选中的产品批量上架','批量上架操作', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
            }).then(() =>{
        // 调取接口
        goodsApi.updateGoods({'goodIds': data, 'goodStatus': '0'}).then(res=>{
            if(res.code == 0){
                this.$message({
                    type: 'success',
                    message: '上架成功'
                });
               this.queryGoodsList() 
            }
        })
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消上架'
                });          
            })
    },
    //批量下架
    pulloffsale(){
         let param=[]
         this.multipleSelection.forEach(function(x){
            param.push(x.id)})

             this.$confirm('是否确认将选中的产品批量下架','批量下架操作', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
            }).then(() =>{
        // 调取接口
        goodsApi.updateGoods({'goodIds': param, 'goodStatus': '1'}).then(res=>{
            if(res.code = '0'){
                this.$message({
                    type: 'success',
                    message: '下架成功'
                });
                this.queryGoodsList()
            }
        })
        }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消下架'
                });          
            })
    },
       //单个下架
        OfftheShelf(index, row){
            console.log(row)
            console.log(this.multipleSelection)
            this.$confirm('是否确认将选中的产品下架','提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
            }).then(() => {
                // 调取接口
                goodsApi.updateGoods({'goodIds': [row.id], 'goodStatus': '1'}).then(res=>{
                    console.log(res)
                    if(res.code = '0'){
                        this.$message({
                            type: 'success',
                            message: '下架成功'
                        });
                        this.queryGoodsList()
                    }
                })
                
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消下架'
                });          
            });
        },
        //单个上架
        grounding(index,row){
            // console.log(this.multipleSelection)
            this.$confirm('是否确认将选中的产品上架','提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            }).then(() => {
            goodsApi.updateGoods({'goodIds': [row.id],'goodStatus': '0'}).then(res=>{
                console.log(res)
                if(res.code="0"){
                    this.$message({
                    type: 'success',
                    message: '上架成功!'
                    });
                    if(this.index == "2"){
                        this.tabChanged()
                    }else if(this.index == "1"){
                        this.tabthree()
                    }else{
                        this.tabsecond()
                    }
                    this.queryGoodsList()
                }
            })
            }).catch(() => {
            this.$message({
                type: 'info',
                message: '已取消上架'
            });          
            });
        },
        //删除
         handleDelete(index, row){
             goodsApi.delGoods(row.id).then(res=>{
                    if(res.code="0"){
                        this.$confirm('是否确认将选中的产品删除',"删除操作" ,{
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        })
                        .then(() => {
                        this.$message({
                            type: 'success',
                            message: '删除成功!'
                        })
                         this.queryGoodsList()
                        }).catch(() => {
                        this.$message({
                            type: 'info',
                            message: '已取消删除'
                        })           
                    })
                    }
             })
      
        },
        handleSelectionChange(val) {
            this.multipleSelection = val;
            console.log(this.multipleSelection)
            if(this.multipleSelection.length>0){
              this.isshow=false
            }else{
                  this.isshow=true
            }
      },
      //排序
        sort(index,row){
            console.log(row)
            this.dialogVisible = true
            // this.sortNumber = 2
            this.selectRow = row  
        },
        submitDia(){
            this.dialogVisible = false
            let obj = {
                id: Number(this.selectRow.id),
                position: Number(this.sortNumber)
            }
            console.log('排序', obj)
            goodsApi.sortGoods(obj)
            .then(res=>{
                 if(res.code== "0"){    
                      this.$message({
                            type: 'success',
                            message: '排序成功!'
                        }) 
                        this.queryGoodsList()
                }
            })
        },
        handleSizeChange(val) {
            console.log(`每页 ${val} 条`);
            this.pageSize=val;
            this.queryGoodsList();
        },
        handleCurrentChange(val) {
            this.pageNum = val;
            this.queryGoodsList();
        },
          //上传文件
        successUp(res,file,fileList) {
            console.log(res,'11')
                this.$refs.upd.clearFiles();
            // this.isUpd = false;
            if(res.code="0"){
                 this.$message({
                type: "success",
                message: "上传成功!",
                });
                this.queryGoodsList();
            }else{
                return false
            }
           
            // // this.ruleForm.picUrl = val.slice(49);
            // // this.img = val;
            // let obj={
            //     flie:this.flie,
            // }
            // goodsApi.batchGoods({flie:this.flie}).then(res=>{
            //     console.log(obj)
            //     if(res.code=0){
            //         alert(123)
            //     }
            // })
            // console.log(file);
            // this.$refs.upd.clearFiles();
            // // this.isUpd = false;
            // this.$message({
            //     type: "success",
            //     message: "上传成功!",
            // });
        },
         //上传文件验证
        beforeUpd(file) {
            console.log(file,'111')
            var suffix=''
            try { 
               var flieArr=file.name.split('.')
                suffix = "."+flieArr[flieArr.length-1]
            } catch(err){
                suffix=''
            }
            if(!/^.*\.(?:xls|xlsx)$/.test(suffix)){
                this.$message.warning("上传模板只能是 xls、xlsx格式!");
                this.files = file
                return  false
            }
            this.files = file
            return 

            // const _this = this;
            // _this.fileList = [];
            // _this.files = file;
            // const extension = file.name.split(".")[1] === "xls";
            // const extension2 = file.name.split(".")[1] === "xlsx";
            // console.log(file);
        //  if (!extension && !extension2) {
        //     _this.$message.warning("上传模板只能是 xls、xlsx格式!");
        // }
        //    this.flie=flie
        //    return null; 
        }
    //    }
        
    }
};
</script>

<style scoped lang="scss">
.goods-kind{
    padding: 20px;
  .el-form-item {
      flex:1;
    .el-input {
      width: auto;
    }
  } 
  .col{
    width: 80px;
    height:60px;
  }
  .btns {
    margin-top: 40px;
  }
 .tab{
     width:120px;
 }
img{
    width:60px;
    height:60px;
    }
}      
.flexCenter {
    display: flex;
    align-items: center;
    margin: 20px 10px 0 0;
    span {
      margin-right: 5px;
      font-size: 14px;
    }
    .ipts,
    .bot {
      width: 200px;
    }
  }

.el-form{
      display: flex;
    //   justify-content: center;
      align-items: center;
      height:160px;
}
.active{
    color:rgb(16,163,255);
    border-bottom:1px solid rgb(16,163,255);
}
.btn{
    text-align: right;
    margin-top: 20px;
}
</style>
